package com.cdu.guoxinan.www.smartcom.aop;

import com.cdu.guoxinan.www.smartcom.domian.pojo.User;
import com.cdu.guoxinan.www.smartcom.domian.pojo.UserLog;
import com.cdu.guoxinan.www.smartcom.mapper.LogMapper;
import com.cdu.guoxinan.www.smartcom.mapper.UserMapper;
import com.cdu.guoxinan.www.smartcom.unit.Data.OperationLogRecord;
import com.cdu.guoxinan.www.smartcom.util.JwtUtil;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class OperationLogService {

    // 实际项目中注入DAO或LogRepository
    @Resource
    private LogMapper logMapper;
    @Resource
    private UserMapper userMapper;

    // 获取当前请求的user_id
    public Long getCurrentUserId() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) return null;
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        if (token == null || token.isEmpty()) return null;
        String username = JwtUtil.getUsername(token);
        if (username == null) return null;
        User user = userMapper.findByUsername(username);
        return user != null ? user.getUserId() : null;
    }
    @Async // 异步保存，不影响主业务
    public void saveLog(OperationLogRecord logRecord) {
        // 1. 打印日志到控制台
        System.out.println("[操作日志] " + logRecord);

        // 2. 保存到数据库
        logMapper.saveLog(convertToEntity(logRecord));
        // 3. 保存到本地文件
        String logFilePath = "logs/operation.log"; // 文件路径
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String logLine = String.format("[%s] %s | 用户ID: %d | 结果: %s | 错误信息: %s%n",
                sdf.format(new Date()),
                logRecord.getDescription(),
                logRecord.getUserId(),
                logRecord.getSuccess(),
                logRecord.getErrorMsg());

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(logFilePath, true))) {
            writer.write(logLine);
        } catch (IOException e) {
            System.err.println("❌ 写入日志文件失败：" + e.getMessage());
        }
    }

    // 转换方法示例
    private UserLog convertToEntity(OperationLogRecord record) {
        UserLog entity = new UserLog();
        entity.setAction(record.getDescription());
        entity.setTimestamp(record.getOperateTime());
        entity.setUserId(record.getUserId());
        entity.setResult(record.getSuccess());
        entity.setInformation(record.getErrorMsg());
        return entity;
    }
}